package com.lydms.service.impl;

import com.lydms.dao.EnglishDao;
import com.lydms.dao.TimingDao;
import com.lydms.pojo.English;
import com.lydms.pojo.Timing;
import com.lydms.pojo.TimingQuery;
import com.lydms.service.TranslateService;
import com.lydms.service.WordAddService;
import com.lydms.service.WordSelectService;
import net.minidev.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class WordAddServiceImpl implements WordAddService {
    private static final Logger logger = LogManager.getLogger(WordAddServiceImpl.class);


    @Autowired
    private EnglishDao englishDao;

    @Autowired
    private TimingDao timingDao;

    @Autowired
    private TranslateService translateService;

    @Autowired
    private WordSelectService wordSelectService;

    //翻译为中文
    private String transToZh = "zh";

    @Value(value = "${category}")
    private Integer category;

    /**
     * 添加英语单词
     *
     * @param en
     * @return null：数据库中已经存在当前数据
     * remark:3:数据库存入异常
     * remark:2:数据翻译失败
     */
    @Override
    public English addEnglish(English en) {
        logger.info("存入的内容为===================================:{}", en.toString());
        String english = en.getEnglish();

//        2.1、查询数据库中是否含有该单词
        English contain = wordSelectService.selectOneByEnglish(english);
        if (contain == null) {
            logger.info("查询数据库是否有该词，内容为：" + contain);

            String chinese1 = en.getChinese();
            String codechinese = en.getCodechinese();
            if (chinese1 == null || codechinese == null) {
//        2.2、将英语进行翻译
                logger.info("没有指定翻译结果，调用翻译接口继续翻译");
                String chinese = translateService.translate(english, transToZh);
                logger.info("翻译以后内容为：" + en);
                en.setChinese(chinese);
            }

//        2.3、存入数据库
            int i = saveDataBase(en);
            if (i == 1) {
//             存入数据库成功
                return en;
            } else {
//            存入数据库失败
                en.setRemark("3");
                return en;
            }
        } else {
//            数据库有当前值
            return null;
        }
    }


    /**
     * 2.3、存入数据库
     *
     * @param en
     * @return
     */
    @Override
    public int saveDataBase(English en) {
        int result = englishDao.insertSelective(en);
        logger.info("插入数据库后返回的结果为 :{}", result);
        return result;
    }

    @Override
    public JSONObject addTimingEnglish(List<English> enList) {
//        1、从数据库中间表中，查询出来当前的分类和日期
        Timing timingData = getTimindData();
        Integer day =timingData.getDay();

//        2、对接收的值，进行取英文处理
        JSONObject json = new JSONObject();
        for (int i = 0; i < enList.size(); i++) {
            English en = enList.get(i);
            String englishOnce = en.getEnglish();
            logger.info("存入的单词为:{}",englishOnce);
            en.setCategory(category);
            en.setDay(day);
            English result = addEnglish(en);
            try {
//                休眠1s
                Thread.sleep(100L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

//        3、对返回值进行判断
            if (result == null) {
                logger.info(englishOnce + "在数据库中已经存在");
                json.put(englishOnce, "数据库中已存入当前单词");
                continue;
            } else {
                if ("2".equals(result.getRemark())) {
                    logger.info("数据翻译失败");
                    json.put(englishOnce, "数据翻译失败");
                    continue;
                }
                if ("3".equals(result.getRemark())) {
                    logger.info("存入数据库异常");
                    json.put(englishOnce, "存入数据库异常");
                    continue;
                }
            }
//            封装返回值
            JSONObject onceJson = new JSONObject();
            onceJson.put("result", true);
            onceJson.put("category", en.getCategory());
            onceJson.put("day", day);
            json.put(englishOnce, onceJson);

            day = checkDay(day);
        }
        timingData.setDay(day);
        int result = addTiming(timingData);
        logger.info("向中间中插入的时间为:{},结果为:{}", day, result);
        return json;
    }

    /**
     * 对日期进行合理性检测（1~30）
     *
     * @param day
     * @return
     */
    @Override
    public Integer checkDay(Integer day) {
        if (day == 30) {
            return 1;
        } else {
            day++;
            return day;
        }
    }


    /**
     * 向Timing数据库中插入数据
     *
     * @param timing
     * @return
     */
    @Override
    public int addTiming(Timing timing) {
        int insert = timingDao.updateByPrimaryKey(timing);
        return insert;
    }

    /**
     * 获取中间表中的当前分类应该插入的时间
     * @return
     */
    private Timing getTimindData(){
        TimingQuery query = new TimingQuery();
        TimingQuery.Criteria criteria = query.createCriteria();
        criteria.andCategoryEqualTo(category);
        List<Timing> timings = timingDao.selectByExample(query);
        Timing timing = timings.get(0);
        return timing;
    }

}
